package com.edu.udistrital.indexing;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import com.edu.udistrital.indexing.document.DocumentIndex;


public class Indexer {

	private final boolean CREATE;
	private final String INDEX_PATH;
	private final String DOCS_PATH;
	
	public enum TipoIndexacion {APRENDIZAJE, CATEGORIZACION};
	
	private Directory directory = null;
	private IndexWriter writer = null;
	private DocumentIndex documento = null;
	
	/**
	 * 
	 */
	public Indexer(String indexPath, String docsPath, boolean create) {
		this.INDEX_PATH = indexPath;
		this.DOCS_PATH = docsPath;
		this.CREATE = create;
	}

	public void indexarDocumentos(TipoIndexacion tipoIndexacion) throws Exception {
		IndexerFactory indexerFabrica = null;
		
		File docDir = new File(DOCS_PATH);
		   
		if (!docDir.exists() || !docDir.canRead()) {
	        System.out.println("Directorio '" +docDir.getAbsolutePath()+ "' no existe, favor verificar");
	        System.exit(1);
	      }

		directory = FSDirectory.open(new File(INDEX_PATH));
		
		if(tipoIndexacion.equals(TipoIndexacion.APRENDIZAJE)) {
			indexerFabrica = new LearningIndexer();
		} else if(tipoIndexacion.equals(TipoIndexacion.CATEGORIZACION)) {
			indexerFabrica = new ClassificationIndexer();
		}
		
		Analyzer analyzer = indexerFabrica.fabricarAnalyzer(Version.LUCENE_36, IndexerFactory.SPANISH);
		documento = indexerFabrica.fabricarDocumento();
		
		IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_36, analyzer);
	
		if (CREATE) {
			iwc.setOpenMode(OpenMode.CREATE);
		} else {
		    iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
		}
		    
		writer = new IndexWriter(directory, iwc);
		
		File file = new File(DOCS_PATH);
		indexDocs(file);
	}
	
	private void indexDocs(File file) throws Exception {
		if (file.canRead()) {
			File[] files = file.listFiles();
			
			for (int i = 0; i < files.length; i++) {
				File f = files[i];
				if (f.isDirectory()) {
					indexDocs(f);
				} else if (!f.isHidden() && f.exists() && acceptFile(f)) {
					indexFile(f);
				}
			}
		}	
	}
	
	private void indexFile(File f) throws Exception {
//		System.out.println("Indexing " + f.getCanonicalPath());
		Document doc = documento.obtenerDocumento(f);
		
        if (writer.getConfig().getOpenMode() == OpenMode.CREATE) {
            System.out.println("adding " + f);
            writer.addDocument(doc);
          } else {
            System.out.println("updating " + f);
            writer.updateDocument(new Term("path", f.getPath()), doc);
          }
	}
	
	private boolean acceptFile(File f) {
		return f.getName().endsWith(".txt");
//		return f.getName().endsWith(".pdf");
	}
	
	public void close() throws IOException {
		if(writer != null) {
			writer.close();
		}	
	}

	/**
	 * @return the directory
	 */
	public Directory getDirectory() {
		return directory;
	}

	/**
	 * @param directory the directory to set
	 */
	public void setDirectory(Directory directory) {
		this.directory = directory;
	}
}
